import sys
import os
import logging
from executer import common
import resultcommit
import uploadfile

def ScriptExecuter(queue, uploadconfig, templateid, taskid, subid, runpath, info, args):
    reload(sys)
    sys.setdefaultencoding('GB18030')
    cwd =  os.getcwd()
    os.chdir(runpath)
    
    logging.basicConfig(filename = 'task.log', 
                                format='%(asctime)s %(levelname)-8s %(message)s',
                                datefmt='%Y%b%d %H:%M:%S',
                                level = logging.DEBUG)
    
    logging.info('task script begin run')
    logging.info(str(info))
    
    file_name = os.path.join(cwd, common.LOCAL_SVN_PATH, info['scriptname'])
    info_for_caller = {}
    
    logging.info(args)
    logging.info(type(args))
    if args != None:
        sys.argv.extend(args.split())
    logging.info(str(sys.argv))
    
    info_for_caller['message'] = ''
    info_for_caller['addtional_mail_receiver'] = ""
    
    try:
        execfile(file_name,  globals())
        globals()['main']()
        
        logging.info(resultcommit.GetResult())
        if resultcommit.GetResult() == True:
            info_for_caller['result'] = common.SUCCESS
        else:
            info_for_caller['result'] = common.FAILURE
        
        if len(resultcommit.GetMessage()) != 0 :
            info_for_caller['message'] = 'script message : ' + resultcommit.GetMessage()
    except SystemExit:
        logging.warn('script should`t have system exit')
        info_for_caller['result'] = common.EXCEPTION
        info_for_caller['message'] = info_for_caller['message']  + '\n excute error : script should`t have system exit'
    except Exception as e:
        logging.exception(e)
        info_for_caller['result'] = common.EXCEPTION
        info_for_caller['message'] =  info_for_caller['message']  + '\n excute error : ' + str(e)
    
    resutl, message = uploadfile.UploadFile(uploadconfig, 
                                            templateid, taskid, subid, 
                                            resultcommit.GetUploadFiles(),
                                            resultcommit.GetCaseResultFiles(),
                                            resultcommit.GetMailAddtionalContent())
    if len(message) != 0 :
        info_for_caller['message'] = info_for_caller['message']  + '\n update file error :' + message
        
    if resultcommit.GetAddtionanlMailReceiver() != "":
        info_for_caller['addtional_mail_receiver'] = resultcommit.GetAddtionanlMailReceiver() 
    
    queue.put(info_for_caller)
